package com.pinyoumei.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.adapter.LuckListAdapter;
import com.pinyoumei.app.bean.LuckClickBean;
import com.pinyoumei.app.bean.LuckInitBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.view.LuckMarqueeView;
import com.pinyoumei.app.view.LuckPan.MultiMiyagiRaffle;
import com.pinyoumei.app.view.Marquee;
import com.pinyoumei.app.view.ScrollSpeedLinearLayoutManger;
import com.pinyoumei.app.view.dialog.BaseDialog;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2021-08-11.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-11        Administrator             新增Person类
 * 2021-08-11        Administrator             增加sex属性
 * 幸运转盘
 */
public class LuckPanActivity extends BaseActivity implements View.OnClickListener {



    private List<Marquee> marquees = new ArrayList<>();
    private LuckMarqueeView marqueeView;
    private boolean isRegister = false;
    private TextView tv_lucky_active_num;
    private TextView tv_user_lucky_num;
    private LuckListAdapter luckListAdapter;
    private RecyclerView recycleView;
    private boolean is_run = false;
    private List<LuckInitBean.ResultBean.PrideListBean> pride_list = new ArrayList<>();
    private LuckRecyclerViewAdapter luckRecyclerViewAdapter;
    private BaseDialog baseDialog;
    private LuckClickBean luckClickBean;
    private RecyclerView rv_2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_luck_pan);

        InitWidget();

        InitData();

    }


    private void InitWidget() {

        RelativeLayout relativeFinish = findViewById(R.id.relative_finish);
        relativeFinish.setOnClickListener(this);
        TextView tv_record = findViewById(R.id.tv_record);
        tv_record.setOnClickListener(this);



        marqueeView = findViewById(R.id.marqueeView);
        tv_lucky_active_num = findViewById(R.id.tv_lucky_active_num);
        tv_user_lucky_num = findViewById(R.id.tv_user_lucky_num);

        rv_2 = findViewById(R.id.rv_2);
        ScrollSpeedLinearLayoutManger scrollSpeedLinearLayoutManger = new ScrollSpeedLinearLayoutManger(this);
        rv_2.setLayoutManager(scrollSpeedLinearLayoutManger);
        luckListAdapter = new LuckListAdapter(R.layout.item_luck_list, null);
        luckListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rv_2.setAdapter(luckListAdapter);


        recycleView = findViewById(R.id.recycleView);
        //先初始化几行几列
        MultiMiyagiRaffle.LINE = 4;
        MultiMiyagiRaffle.COLUMN = 4;
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(MultiMiyagiRaffle.COLUMN, StaggeredGridLayoutManager.VERTICAL);
        recycleView.setLayoutManager(manager);


    }




    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.relative_finish:
                finish();
                break;

            case R.id.tv_record:
                startActivity(new Intent(LuckPanActivity.this, LuckRecordActivity.class));
                break;

            default:
                break;
        }
    }


    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(LuckPanActivity.this));


        OkGo.<String>post(Constants.LUCKY_INIT)
                .params("user_id", SPUtils.getAppUserId(LuckPanActivity.this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {




                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        LuckInitBean luckInitBean = gson.fromJson(response.body(), LuckInitBean.class);

                        if (luckInitBean.getCode() >= 0) {
                            List<LuckInitBean.ResultBean.Note_list> note_list = luckInitBean.getResult().getNote_list();
                            if (note_list != null && note_list.size() > 0) {
                                for (int i = 0; i < note_list.size(); i++) {
                                    Marquee marquee = new Marquee();
                                    marquee.setImgUrl(note_list.get(i).getUser_head_img());
                                    marquee.setTitle(note_list.get(i).getNote_str());
                                    marquees.add(marquee);
                                }
                                marqueeView.setImage(true);
                                marqueeView.startWithList(marquees);
                            }
                            tv_lucky_active_num.setText("今日剩余抽奖次数：" + luckInitBean.getResult().getLucky_active_num() + "次");
                            tv_user_lucky_num.setText("幸运值：" + luckInitBean.getResult().getUser_lucky_num());

                            List<LuckInitBean.ResultBean.PrideUserList> pride_user_list = luckInitBean.getResult().getPride_user_list();
                            if (pride_user_list != null && pride_user_list.size() > 0) {
                                luckListAdapter.setNewData(pride_user_list);


                                Handler handler = new Handler();
                                Runnable runnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        if (isRegister){
                                            isRegister = false;
                                            rv_2.smoothScrollToPosition(0);
                                            handler.postDelayed(this,3000);//延时五百毫秒，再次执行这个runnable，如果isRegister为false了就停止执行了
                                        }else{
                                            isRegister = true;
                                            rv_2.smoothScrollToPosition(pride_user_list.size()-1);
                                            handler.postDelayed(this,3000);
                                        }
                                    }
                                };


                                handler.postDelayed(runnable,1500);//延时五百毫秒，执行runnable

//                                new Thread(){
//                                    @Override
//                                    public void run() {
//                                        SystemClock.sleep(1000);
//
//                                        rv_2.smoothScrollToPosition(pride_user_list.size()-1);
//                                    }
//                                }.start();

                            }

                             List<LuckInitBean.ResultBean.PrideListBean> list = luckInitBean.getResult().getPride_list();
                            sort_num(list);


                            luckRecyclerViewAdapter = new LuckRecyclerViewAdapter(recycleView, LuckPanActivity.this.pride_list, LuckPanActivity.this, new MultiMiyagiRaffle.OnLuckAnimationEndListener() {
                                @Override
                                public void onLuckAnimationEnd(int pos, String msg) {
                                    //打印抽奖结果
                                    is_run = false;
                                    if (luckClickBean!=null){
                                        RelashData();
                                        baseDialog = new BaseDialog(LuckPanActivity.this,R.layout.dialog_luck);

                                        baseDialog.show();
                                        TextView tv_prideName = baseDialog.findViewById(R.id.tv_prideName);
                                        tv_prideName.setText(luckClickBean.getResult().getPride_info().getPrideName()+"");

                                        TextView tv_lucky_active_num = baseDialog.findViewById(R.id.tv_lucky_active_num);
                                        tv_lucky_active_num.setText(luckClickBean.getResult().getLucky_active_num()+"");
                                        Button bt_record = baseDialog.findViewById(R.id.bt_record);
                                        bt_record.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                startActivity(new Intent(LuckPanActivity.this, LuckRecordActivity.class));

                                            }
                                        });

                                        ImageView iv_close = baseDialog.findViewById(R.id.iv_close);
                                        iv_close.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                baseDialog.dismiss();
                                            }
                                        });
                                    }
//                                    ToastUtils.showShort(LuckPanActivity.this.pride_list.get(pos).getSort()+"");
                                }
                            });


                            recycleView.setAdapter(luckRecyclerViewAdapter);

                            findViewById(R.id.iv_start).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                    if (is_run == false){

                                        LuckClick();
                                    }
                                }
                            });


                        } else {
                            Toast.makeText(LuckPanActivity.this, luckInitBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }



    private void RelashData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(LuckPanActivity.this));


        OkGo.<String>post(Constants.LUCKY_INIT)
                .params("user_id", SPUtils.getAppUserId(LuckPanActivity.this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {




                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        LuckInitBean luckInitBean = gson.fromJson(response.body(), LuckInitBean.class);

                        if (luckInitBean.getCode() >= 0) {
                            marqueeView.removeAllViews();
                            List<LuckInitBean.ResultBean.Note_list> note_list = luckInitBean.getResult().getNote_list();
                            if (note_list != null && note_list.size() > 0) {
                                for (int i = 0; i < note_list.size(); i++) {
                                    Marquee marquee = new Marquee();
                                    marquee.setImgUrl(note_list.get(i).getUser_head_img());
                                    marquee.setTitle(note_list.get(i).getNote_str());
                                    marquees.add(marquee);
                                }
                                marqueeView.setImage(true);
                                marqueeView.startWithList(marquees);
                            }
                            tv_lucky_active_num.setText("今日剩余抽奖次数：" + luckInitBean.getResult().getLucky_active_num() + "次");
                            tv_user_lucky_num.setText("幸运值：" + luckInitBean.getResult().getUser_lucky_num());

                            List<LuckInitBean.ResultBean.PrideUserList> pride_user_list = luckInitBean.getResult().getPride_user_list();
                            if (pride_user_list != null && pride_user_list.size() > 0) {
                                luckListAdapter.setNewData(pride_user_list);
                            }

                        } else {
                            Toast.makeText(LuckPanActivity.this, luckInitBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }


    private void LuckClick() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(LuckPanActivity.this));


        OkGo.<String>post(Constants.LUCKY_DRAWNOW)
                .params("user_id", SPUtils.getAppUserId(LuckPanActivity.this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        luckClickBean = gson.fromJson(response.body(), LuckClickBean.class);

                        if (luckClickBean.getCode() >= 0) {

                            is_run = true;
                            //抽中奖项
                            int num = luckClickBean.getResult().getPride_info().getSort();

                            for (int i=0;i<pride_list.size();i++) {
                                if (pride_list.get(i).getSort() == num) {
                                    luckRecyclerViewAdapter.multiMiyagiRaffle.setLuckNum(i);
                                }
                            }
                            luckRecyclerViewAdapter.multiMiyagiRaffle.startAnim();

                        } else {
                            Toast.makeText(LuckPanActivity.this, luckClickBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }


    public class LuckRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private String TAG = "LuckRecyclerViewAdapter";
        private RecyclerView recyclerView;


        private Context c;

        public LuckRecyclerViewAdapter(RecyclerView recyclerView, List<LuckInitBean.ResultBean.PrideListBean> list, Context c, MultiMiyagiRaffle.OnLuckAnimationEndListener listener) {
            this.c = c;
            this.recyclerView = recyclerView;

            multiMiyagiRaffle = new MultiMiyagiRaffle(list, new MultiMiyagiRaffle.StatusChange() {
                @Override
                public void changeClose(int position, boolean ischeck) {
                    itemChangeClose(position, ischeck);
                }
            });
            multiMiyagiRaffle.setLuckAnimationEndListener(listener);
        }

        public MultiMiyagiRaffle multiMiyagiRaffle;


        @Override

        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder viewHolder;
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_luck, parent, false);
            viewHolder = new ViewHolder(view);


            return viewHolder;

        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

            if (multiMiyagiRaffle.luckMap.containsKey(position)) {
                LuckInitBean.ResultBean.PrideListBean giftBean = (LuckInitBean.ResultBean.PrideListBean) multiMiyagiRaffle.luckMap.get(position);
                ViewHolder viewHolder = (ViewHolder) holder;
//                viewHolder.iv_luck.setImageDrawable(ContextCompat.getDrawable(c,giftBean.getImagPath()));
//                viewHolder.tv_value.setText(position+"");
//                viewHolder.tv_list.setText(giftBean.getGiftName());
//


                Glide.with(mContext).load(giftBean.getPride_img()).into(viewHolder.iv_luck);
                viewHolder.Container.setSelected(giftBean.isCheked());

            }


        }


        @Override
        public int getItemViewType(int position) {

            if (multiMiyagiRaffle.luckMap.containsKey(position)) {
                return 1;
            } else return -1;
            // return position;
        }


        @Override

        public int getItemCount() {
            return MultiMiyagiRaffle.COLUMN * MultiMiyagiRaffle.LINE;

        }


        class ViewHolder extends RecyclerView.ViewHolder {

            //            TextView tv_value,tv_list;
            ImageView iv_luck;
            RelativeLayout Container;

            ViewHolder(View itemView) {
                super(itemView);
//                tv_value=itemView.findViewById(R.id.tv_value);
                iv_luck = itemView.findViewById(R.id.iv_luck);
                Container = itemView.findViewById(R.id.Container);
//                tv_list=itemView.findViewById(R.id.tv_list);
            }

        }


        private void itemChangeClose(int position, boolean ischeck) {
            LuckRecyclerViewAdapter.ViewHolder viewHolder = (LuckRecyclerViewAdapter.ViewHolder) recyclerView.findViewHolderForAdapterPosition(position);
//            viewHolder.Container.setSelected(ischeck);
            if (ischeck) {
                viewHolder.Container.setBackground(ContextCompat.getDrawable(LuckPanActivity.this, R.drawable.shanpe_red_select_5dp));
            } else {
                viewHolder.Container.setBackground(null);
            }
        }
    }
    private void sort_num(List<LuckInitBean.ResultBean.PrideListBean> list) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                switch (list.get(i).getSort()) {
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        pride_list.add(list.get(i));
                        break;
                    case 5:
                        pride_list.add(list.get(5));
                        break;
                    case 6:
                        pride_list.add(list.get(7));
                        break;
                    case 7:
                        pride_list.add(list.get(11));
                        break;
                    case 8:
                        pride_list.add(list.get(10));
                        break;
                    case 9:
                        pride_list.add(list.get(9));
                        break;
                    case 10:
                        pride_list.add(list.get(8));
                        break;
                    case 11:
                        pride_list.add(list.get(6));
                        break;
                    case 12:
                        pride_list.add(list.get(4));
                        break;
                    default:
                        break;
                }

            }
        }
    }
}
